// Copyright (C) 2012 Tanmay Sinha
// All rights reserved

package org.saakshar.utils;

import static org.saakshar.utils.StringUtils.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

/**
 * 
 * Utility class for handling HTTP requests
 * 
 * @author tanmay
 * 
 */
public class HttpReqestUtils {

	/** The Tag */
	private static final String TAG = HttpReqestUtils.class.getSimpleName();

	private HttpReqestUtils() {
		// Prevent instantiation
	}

	/**
	 * Utility method that created the HttpGet object using the URI parameter
	 * 
	 * @param uri
	 *            the requested uri
	 * @return the response as string
	 */
	public static String executeGetRequest(String uri) {
		if (!isBlank(uri)) {
			HttpGet httpGet = new HttpGet(uri);
			return executeGetRequest(httpGet);
		}

		return null;
	}

	/**
	 * Execute GET request and return string as response. This method could
	 * return <code>null</code>. This method should be used when headers are
	 * required to be set in the request.
	 * 
	 * @param httpGet
	 *            the HTTP GET request
	 * 
	 * @return the response as string
	 */
	public static String executeGetRequest(HttpGet httpGet) {

		if (httpGet != null) {
			HttpClient client = new DefaultHttpClient();

			StringBuilder builder = new StringBuilder();

			try {
				HttpResponse response = client.execute(httpGet);
				StatusLine statusLine = response.getStatusLine();
				int statusCode = statusLine.getStatusCode();
				if (statusCode == 200) {
					HttpEntity entity = response.getEntity();
					InputStream content = entity.getContent();
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(content));
					String line;
					while ((line = reader.readLine()) != null) {
						builder.append(line);
					}
				} else {
					Log.e(TAG, "Request failed with Status: " + statusCode);
				}
			} catch (ClientProtocolException e) {
				Log.e(TAG, "Client protocol exception for URL - "
						+ httpGet.getURI().toString());
			} catch (IOException e) {
				Log.e(TAG, "Failed to retrieve content from URL - "
						+ httpGet.getURI().toString());
			}
			return builder.toString();
		}

		return null;
	}

}
